﻿using BingoClientModel;
using BingoHallServerConsole.Helper.Account;
using BingoServerCommon.Common;
using Dapper;
using MySql.Data.MySqlClient;


namespace BingoHallServerConsole.Business.Account
{
	/// <inheritdoc />
	public class CS_LoginAnonymous : Package
	{
		public CS_LoginAnonymous(EnumPackCommand mainid) : base(mainid)
		{
		}

		public CS_LoginAnonymous(byte[] buffer, int len) : base(buffer, len)
		{
		}

		public override Package Clone(byte[] bytes)
		{
			return new CS_LoginAnonymous(bytes, bytes.Length);
		}


		/// <summary>
		/// 
		/// </summary>
		public override void Excute(Session session)
		{
			var guid = ReadString();

			MySqlConnection conn = Program.ConnectionPool.getConnection(); //从连接池拿到一个连接
			var package = new Package(EnumPackCommand.SC_AnonymousLogin_Ret);

			//如果guid为空，则新建用户
			if (string.IsNullOrEmpty(guid))
			{
				string sql = $"SELECT * from players p WHERE p.guid = '{guid}';";
				var player = conn.QueryFirstOrDefault<Player>(sql);

				if (player != null)
				{
					//0表示成功，其余是失败
					package.Write((byte)EnumReqRetStatus.Success);
					//int，用户id
					package.Write(player.id);
					//string，account
					package.Write(player.account);
					//string，昵称
					package.Write(player.nickname);
					//string ，头像
					package.Write(player.portrait);
					//int 经验值
					package.Write(player.exp);
					//int，入场券数目
					package.Write(player.admission_ticket_num);
					//int，道具数目
					package.Write(player.props_num);
					//int，拼图数值1
					package.Write(player.jigsaw_1_num);
					//int，拼图数值2
					package.Write(player.jigsaw_2_num);
				}
				else
				{
					//非0是失败
					package.Write((byte)EnumReqRetStatus.Fail0);
				}
			}
			//否则则查询用户信息
			else
			{
				var newPlayId = AccountHelper.AddOneAnonymousPlayer();
				if (newPlayId > 0)
				{
					package.Write((byte)EnumReqRetStatus.Success);
					package.Write(newPlayId);
				}
				else
				{
					//非0是失败
					package.Write((byte)EnumReqRetStatus.Fail0);
				}
			}

			session.Send(package);

			Program.ConnectionPool.returnConnection(conn);//连接用完回收
		}
	}
}
